#include "socket.h"
#include <stdlib.h>
#include <iostream>
#include <unistd.h>

int main(int argc, char* argv[]) {
    if (argc != 2) {
        std::cerr << "usage: %s <port>" << std::endl;
    }

    TcpServer s = TcpServer();
    std::string buffer;

    if (!s.serverInit(atoi(argv[1]))) {
        std::cerr << "server init failed" << std::endl;
        return -1;
    }

    while (true) {
        std::cout << "Waiting for client connection..." << std::endl;
        
        if (!s.accept()) {
            std::cerr << "Server accept failed, retrying..." << std::endl;
            sleep(1);
            continue;
        }

        bool clientConnected = true;
        while (clientConnected) {
            if (s.recv(buffer, 512)) {
                std::cout << "Received from client: " << buffer << std::endl;
                
                if (!s.send(buffer)) {
                    std::cerr << "Failed to send response to client" << std::endl;
                    clientConnected = false;
                }
                
                buffer.clear();
            } else {
                clientConnected = false;
            }
        }
        
        s.closeClient();
    }
    s.closeListen();
    return 0;
}